package com.zyx.shiro;

import com.zyx.shiro.realm.CustomerRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * 使用自定义realm
 */
@Slf4j
public class TestCustomerRealmAuthenticator {
    public static void main(String[] args) {
        // 创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        // 设置自定义realm
        defaultSecurityManager.setRealm(new CustomerRealm());
        // 将安全工具类设置安全工具类
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        // 通过安全工具类获取subject
        Subject subject = SecurityUtils.getSubject();
        // 创建token
        UsernamePasswordToken token = new UsernamePasswordToken("xiaochen", "123");
        try {
            subject.login(token);
            log.info("{}", subject.isAuthenticated());
        } catch (UnknownAccountException ex) {
            log.error("exception: [{}]", ex.getMessage(), ex);
            log.info("用户名错误");
        } catch (IncorrectCredentialsException ex) {
            log.error("exception: [{}]", ex.getMessage(), ex);
            log.info("密码错误");
        }
    }

}
